#include "kernel_operator.h"



// tensor num for each queue
constexpr int32_t BUFFER_NUM = 2;

template<typename TYPE_X,typename TYPE_Y, typename TYPE_Z,bool IsExistBigCore> 
class KernelFmod {
public:
    __aicore__ inline KernelFmod() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR y, GM_ADDR z, uint64_t smallCoreDataNum,
                                uint64_t bigCoreDataNum, uint64_t bigCoreLoopNum, 
                                uint64_t smallCoreLoopNum, uint64_t ubPartDataNum, 
                                uint64_t smallCoreTailDataNum, uint64_t bigCoreTailDataNum, 
                                uint64_t tailBlockNum) 
    {
        ASSERT(AscendC::GetBlockNum() != 0 && "block dim can not be zero!");
        uint64_t coreNum = AscendC::GetBlockIdx();
        uint64_t globalBufferIndex = bigCoreDataNum * AscendC::GetBlockIdx();
        this->ubPartDataNum = ubPartDataNum;
        if constexpr (IsExistBigCore) 
        {
          if (coreNum < tailBlockNum) 
          { 
            this->coreDataNum = bigCoreDataNum;
            this->tileNum = bigCoreLoopNum;
            this->tailDataNum = bigCoreTailDataNum;
          }
          else 
          { 
            this->coreDataNum = smallCoreDataNum;
            this->tileNum = smallCoreLoopNum;
            this->tailDataNum = smallCoreTailDataNum;
            globalBufferIndex -= (bigCoreDataNum - smallCoreDataNum) * (AscendC::GetBlockIdx() - tailBlockNum);
          }
        }
        else
        {
          this->coreDataNum = smallCoreDataNum;
          this->tileNum = smallCoreLoopNum;
          this->tailDataNum = smallCoreTailDataNum;
          globalBufferIndex = smallCoreDataNum * AscendC::GetBlockIdx();
        }
          
        xGm.SetGlobalBuffer((__gm__ TYPE_X*)x + globalBufferIndex, this->coreDataNum);
        yGm.SetGlobalBuffer((__gm__ TYPE_Y*)y + globalBufferIndex, this->coreDataNum);
        zGm.SetGlobalBuffer((__gm__ TYPE_Z*)z + globalBufferIndex, this->coreDataNum);
        pipe.InitBuffer(inQueueX, BUFFER_NUM, this->ubPartDataNum * sizeof(TYPE_X));
        pipe.InitBuffer(inQueueY, BUFFER_NUM, this->ubPartDataNum * sizeof(TYPE_Y));
        pipe.InitBuffer(outQueueZ, BUFFER_NUM, this->ubPartDataNum * sizeof(TYPE_Z));

        pipe.InitBuffer(tmpbuf1 , this->ubPartDataNum * sizeof(TYPE_Z));
        pipe.InitBuffer(tmpbuf2 , this->ubPartDataNum * sizeof(TYPE_Z));
    }
    
    __aicore__ inline void Process()
    {
        int32_t loopCount = this->tileNum;
        this->processDataNum = this->ubPartDataNum;
        for (int32_t i = 0; i < loopCount-1; i++) 
        {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
        this->processDataNum = this->tailDataNum;
        CopyIn(loopCount-1);
        Compute(loopCount-1);
        CopyOut(loopCount-1);
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
      AscendC::LocalTensor<TYPE_X> xLocal = inQueueX.AllocTensor<TYPE_X>();
      AscendC::DataCopy(xLocal, xGm[progress * this->ubPartDataNum], this->processDataNum);
      inQueueX.EnQue(xLocal);

      AscendC::LocalTensor<TYPE_Y> yLocal = inQueueY.AllocTensor<TYPE_Y>();
      AscendC::DataCopy(yLocal, yGm[progress * this->ubPartDataNum], this->processDataNum);
      inQueueY.EnQue(yLocal);
    }

    __aicore__ inline void Compute(int32_t progress)
    {
      AscendC::LocalTensor<TYPE_X> xLocal = inQueueX.DeQue<TYPE_X>();
      AscendC::LocalTensor<TYPE_Y> yLocal = inQueueY.DeQue<TYPE_Y>();
      AscendC::LocalTensor<TYPE_Z> zLocal = outQueueZ.AllocTensor<TYPE_Z>();
    
      auto a=tmpbuf1.Get<TYPE_Z>();
      auto b=tmpbuf2.Get<TYPE_Z>();

      int sz=this->processDataNum;
      //AscendC::Fmod(zLocal,xLocal,yLocal, sz); // z = fmod
      //precision issue, so use z = x - y * floor(x / y) instead of fmod

      AscendC::Abs(a, xLocal, sz); // a = |x|
      AscendC::Abs(b, yLocal, sz); // b = |y|
      AscendC::Div(yLocal, a, b, sz); // y= a / b

      AscendC::Cast(yLocal,yLocal, AscendC::RoundMode::CAST_TRUNC, sz); // y = floor(y)
      AscendC::Mul(yLocal, b, yLocal, sz); // b = y * b

      AscendC::Sub(zLocal, a, yLocal, sz); // z = a - b

      AscendC::Div(a, a, xLocal, sz); // a = x / |x|
      AscendC::Mul(zLocal, zLocal, a, sz); // z = z * a

      outQueueZ.EnQue<TYPE_Z>(zLocal);
      inQueueX.FreeTensor(xLocal);
      inQueueY.FreeTensor(yLocal);
    }
    
    __aicore__ inline void CopyOut(int32_t progress)
    {
      AscendC::LocalTensor<TYPE_Z> zLocal = outQueueZ.DeQue<TYPE_Z>();  
      AscendC::DataCopy(zGm[progress * this->ubPartDataNum], zLocal, this->processDataNum);
      outQueueZ.FreeTensor(zLocal);
    }
private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::QuePosition::VECIN, BUFFER_NUM> inQueueX,inQueueY;
    AscendC::TQue<AscendC::QuePosition::VECOUT, BUFFER_NUM> outQueueZ;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmpbuf1,tmpbuf2;
    AscendC::GlobalTensor<TYPE_X> xGm;
    AscendC::GlobalTensor<TYPE_Y> yGm;
    AscendC::GlobalTensor<TYPE_Z> zGm;
    uint64_t coreDataNum;
    uint64_t tileNum;
    uint64_t ubPartDataNum;
    uint64_t tailDataNum;
    uint64_t processDataNum;
};

extern "C" __global__ __aicore__ void fmod_custom(GM_ADDR x, GM_ADDR y,GM_ADDR z, GM_ADDR workspace, GM_ADDR tiling)
{
    GET_TILING_DATA(tiling_data, tiling);              
    if(TILING_KEY_IS(1))
    {
      KernelFmod<DTYPE_X, DTYPE_Y,DTYPE_OUT, 1 >op;
      op.Init(x,y, z, tiling_data.smallCoreDataNum,
                tiling_data.bigCoreDataNum, tiling_data.bigCoreLoopNum,
                tiling_data.smallCoreLoopNum, tiling_data.ubPartDataNum,
                tiling_data.smallCoreTailDataNum, tiling_data.bigCoreTailDataNum,
                tiling_data.tailBlockNum);
      op.Process();       
    }
    else if(TILING_KEY_IS(0))
    {
      KernelFmod<DTYPE_X, DTYPE_Y,DTYPE_OUT, 0 >op;
      op.Init(x,y, z, tiling_data.smallCoreDataNum,
                tiling_data.bigCoreDataNum, tiling_data.bigCoreLoopNum,
                tiling_data.smallCoreLoopNum, tiling_data.ubPartDataNum,
                tiling_data.smallCoreTailDataNum, tiling_data.bigCoreTailDataNum,
                tiling_data.tailBlockNum);
      op.Process();   
    }
}